Pointer syntax can be
confusing, because pointers can both give the memory location and give the
actual value stored in that same location. When a pointer is declared, the
syntax is this: variable_type *name; Notice the *. This is the key to
declaring a pointer, if you use it before the variable name, it will declare
the variable to be a pointer. There are two ways to use the pointer to access information about the memory address it points to. It is possible to have it give the actual address to another variable, or to pass it into a function. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is dereferencing. In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of the variable, put the & sign in front of the variable name. This makes it give its address. This is called the reference operator, because it returns the memory address. |
|
The cout outputs the value
in x. The integer is called x. A pointer to an integer is then defined as
"pointer". Then it stores the memory location of x in pointer by
using the ampersand (&) symbol. If you wish, you can think of it as if
the jar that had the integer had a ampersand in it then it would output its
name (in pointers, the memory address) Then the user inputs the value for x.
Then the cout uses the * to put the value stored in the memory location of
pointer. If the jar with the name of the other jar in it had a * in front of
it would give the value stored in the jar with the same name as the one in
the jar with the name. It is not too hard, the * gives the value in the
location. The unastricked gives the memory location. |